from django.http import JsonResponse
from drf_spectacular.utils import extend_schema,OpenApiResponse,inline_serializer
from drf_spectacular.types import OpenApiTypes 
from rest_framework import status as ResponseStatus
from rest_framework.decorators import action
from rest_framework.mixins import (ListModelMixin,
                                   RetrieveModelMixin,DestroyModelMixin)
from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from backend.cews.services.TaskService import query_nested_stock_item_task_by_stock_code
from rest_framework import serializers
from utils.autoschema import AutoDocSchema
from utils.decorators import request_data, check_group_permission
from utils.mixins import StockItemTaskUpdateModelMixin 
from utils.mixins import StockItemTaskCreateModelMixin , StockItemTaskDeleteModelMixin

import backend.cews.services.RepairService as RepairService
from backend.cews.models import  StockItem, StockItemTask

from .serializers import (StockItemTaskEformSerializer, StockItemTaskSerializerMain)


class StockItemTaskViewSet(
    RetrieveModelMixin,
    ListModelMixin,
    StockItemTaskUpdateModelMixin,
    GenericViewSet,
    StockItemTaskDeleteModelMixin,
    StockItemTaskCreateModelMixin
):
    serializer_class = StockItemTaskSerializerMain
    queryset = StockItemTask.objects.all()
    
    # @extend_schema(request=StockItemTaskSerializerMain)
    # def create(self, request, *args, **kwargs):.
    #     ## return super().get()
    #     return super().create(request, *args, **kwargs)
    
    # @extend_schema(request=StockItemTaskSerializerMain)
    # def update(self, request, *args, **kwargs):
    #     ## return super().get()
    #     return super().update(request, *args, **kwargs)
    
    
    # @extend_schema(responses={200: StockItemTaskEformSerializer(many=True)})
    @extend_schema(responses={
        200:inline_serializer(
            name='StockItemTaskAllList',
            fields={
                'code':serializers.IntegerField(),
                'data':serializers.ListField(child=StockItemTaskEformSerializer())
            }
        )
    })
    @action(detail=False, methods=["POST"], url_name="get_all_tasks", schema=AutoDocSchema())
    @request_data(keys=['stock_code'])
    def get_all_tasks(self,request,stock_code):
        '''
        desc: Get list of tasks for a stock item, **including child stock item task**
        json:
            stock_code: string
        '''
        try:
            stockItemTasks = query_nested_stock_item_task_by_stock_code(stock_code)
            serializer = StockItemTaskEformSerializer(stockItemTasks, many=True)
            return Response(
                status=ResponseStatus.HTTP_200_OK,
                data={
                    'code':1,
                    'data':serializer.data
                }
            )
        except StockItem.DoesNotExist as ex:
            return JsonResponse(data={
                'code':0,
                'message':str(ex),
            },status=400)
            
 
    @action(detail=False, methods=["POST"], url_name="get_tasks", schema=AutoDocSchema())
    @request_data(keys=['stock_code'])
    def get_tasks(self,request,stock_code):
        '''
        desc: Get list of tasks for a stock item
        json:
            stock_code: string
        '''
        try:
            stock_item = StockItem.objects.get(stock_code=stock_code)
            stockItemTasks = StockItemTask.objects.filter(stock_item=stock_item)
            
            serializer = StockItemTaskEformSerializer(stockItemTasks, many=True)
            
            return Response(
                status=ResponseStatus.HTTP_200_OK,
                data={
                    'code':1,
                    'data':serializer.data
                }
            )
        except StockItem.DoesNotExist as ex:
            return JsonResponse(data={
                'code':0,
                'message':str(ex),
            },status=400)
            
 
